import Sequelize = require('sequelize');
import {Test3} from './model_test3';
import { Delay } from '../task/delay';
import { Test4 } from './model_test4';
export class DBManager
{
    static getSequlize():Sequelize.Sequelize
    {
        return DBManager.data;
    }
    private static data: Sequelize.Sequelize;
    private static state: number = 0;//几个state  1= 初始化中 -1 =error 2.初始化成功
    static async Init(): Promise<void>
    {
        if (DBManager.data != null) 
        {
            while (DBManager.state == 1)//初始化中状态，等待
            {
                await Delay(100);
            }
            if (DBManager.state == -1)
            {
                console.log("db init error.");
            }
            if (DBManager.state == 2)
            {
                console.log("db init already.");
            }
            return;
        }
        var op: Sequelize.Options =
        {
            dialect: "mysql",
            host: "127.0.0.1",
            port: 3306,
        };
        var libname = "testdb";
        var username = "root";
        var password = "";
        DBManager.data = new Sequelize.Sequelize(libname, username, password, op);
        DBManager.state = 1;
        try
        {
            //连接数据库
            await DBManager.data.authenticate();

            //要么成功，要么出错
            console.log("db init.");

            //定义模型，就是配置数据表的样式

            DBManager.state = 2;
        }
        catch (err)
        {
            DBManager.state = -1;
            console.log("db init error.");
        }

        await DBManager.defineModel();

        return;
    }

    static async defineModel(): Promise<void>
    {
        //只保留一种模块初始化方式
        Test3.RegModel();
        Test4.RegModel();

        await DBManager.data.sync();
    }
}



